package cn.tedu.luban.demo.gateway.filters;

import com.alibaba.nacos.common.utils.CollectionUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.server.RequestPath;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.URI;
import java.util.List;

//@Component
public class MyFilter01 implements GlobalFilter, Ordered {
    /** 核心的过滤逻辑执行的方法 主要控制的请求链(请求上下文 请求对象 响应对象)
     *  控制连接上下环境的过滤链
     *  所有进入到网关的请求 只要找到路由映射,就一定会经过这个过滤器
     * @param exchange 包含的是请求和响应的对象封装
     * @param chain 链(连接前后过滤器的关键对象)
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        System.out.println("myfilter01过滤逻辑开始执行");
        //允许请求进入后面的过滤器
        //操作使用请求对象 功能一般都是从请求中读数据
        //1. 获取请求对象 reuqest
        ServerHttpRequest request = exchange.getRequest();
        //2. 从请求对象获取数据--请求路径
        URI uri = request.getURI();//包含请求域名端口的完整路径
        RequestPath path = request.getPath();//只有path
        System.out.println("uri:"+uri);
        System.out.println("path:"+path);
        //3. 请求参数 ?name=wch&age=18
        MultiValueMap<String, String> queryParams = request.getQueryParams();
        //从quereyparam拿到参数
        List<String> ages = queryParams.get("age");//list size=0 list=null
        if (CollectionUtils.isNotEmpty(ages)){
            System.out.println("age:"+ages);
        }
        //4. 请求头获取
        HttpHeaders headers = request.getHeaders();
        //下面的方法等同于 获取Accept请求头
        List<MediaType> accepts = headers.getAccept();
        if (CollectionUtils.isNotEmpty(accepts)){
            System.out.println("accept:"+accepts);
        }
        //获取没有封装方法的头
        List<String> authorization = headers.get("Authorization");
        //5. 获取请求客户端的ip地址
        request.getRemoteAddress();
        //6. 请求的cookie数值 Cookie: key1=value1;key2=value2
        request.getCookies();
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
